<?php

namespace Biz\service\wiki;

use Biz\model\wiki\Wiki as mWiki;
use Biz\tools\TbkUnion;
use Doraemon\tools\Log;
use Biz\model\wiki\WikiSelectionLib as mSelectionLib;
use Doraemon\model\Category;
use Biz\tools\RealUrl;
use Biz\pockets\serviceTrait\_Async;
use Biz\cache\wiki\SelectionLib as CacheSelectionLib;
use Biz\model\wiki\WikiBasic as mWikiBasic;


class SelectionLib
{
    use _Async;

    const PAGESIZE = 20;

    const CATE_MAP_FILE = '/home/adm_rsync_dir/ali_cate.txt';


    public static $cate_map = [];
    /**/
    public static function setCateMap()
    {
        if(file_exists(self::CATE_MAP_FILE)){
           $content =  file_get_contents(self::CATE_MAP_FILE);
           $content = explode("\n" , $content);
           if($content && is_array($content)){
               foreach ($content as $val){
                   if($val){
                       $cate_arr = explode( "，",$val);
                       if($cate_arr && is_array($cate_arr)){
                            $hhz_cate_arr = array_slice($cate_arr , 0 , 4);
                            $hhz_cate_arr = array_filter($hhz_cate_arr);
                             self::$cate_map[$cate_arr[7]] = [
                                'cate_name' => $hhz_cate_arr[count($hhz_cate_arr) -1],
                               'father_cate_name' => $hhz_cate_arr[count($hhz_cate_arr) -2],
                           ];
                       }
                   }
               }
           }
        }
    }
    /*获取 选品库商品信息
     *@params array itemIds
     *@return array  result
     * */
    public static function getGoodsInfoByItemIds($itemIds)
    {
        if(empty($itemIds)) return [];
        $hashPrice = self::getPriceByItemIds($itemIds);
        $info =   mSelectionLib::selectByWhere(['itemId' => $itemIds ,] ,
            [
                'itemId' ,
                'title' ,
                'pic_url' ,
                'small_images' ,
                'shop_name' ,
                'zk_final_price' ,
                'select_status'
            ]);
        $result = [];
        if($info && is_array($info)){
            $hashGoodsInfo = array_combine(array_column($info , 'itemId') , $info);
            foreach($itemIds  as $itemId){
                if($hashPrice[$itemId]){
                    $hashGoodsInfo[$itemId]['zk_final_price']  = $hashPrice[$itemId];
                }
                $result[] = $hashGoodsInfo[$itemId];
            }
       }
        return $result;
    }

    /*获取itemIds 通过page
     *@param int page
     *@param int pagesize
     *@param int min_id
     * @return array itemIds
     * */
    public static function getItemIds($page = 1 , $pageSize=self::PAGESIZE , $min_id = 0 )
    {
        $itemIds  =   mSelectionLib::selectByWhere([
            'id[>]' => $min_id,
            'select_status' => [mSelectionLib::STATUS_WAIT_CHECK , mSelectionLib::STATUS_CHECKED],
            'LIMIT' =>[($page-1) * $pageSize , $pageSize]
        ] , ['id','itemId' ]);
        return $itemIds;
    }

    /*获取price
     *
     * */
    public static function getPriceByItemIds($itemIds)
    {
        if(empty($itemIds)) return [];
        $hashPrice =  CacheSelectionLib::getMulti($itemIds);
        $updateIds = [];
        if($itemIds && is_array($itemIds)){
            foreach($itemIds as $itemId){
                if(empty($hashPrice[$itemId])){
                    $updateIds[] = $itemId;
                }
            }
        }
        self::_async($updateIds);
        return $hashPrice;
    }

    /*异步更新price
     *
     * */
    public static function _async_getPriceByItemIds($itemIds)
    {
        if($itemIds && is_array($itemIds)){
                $ItemsInfo =  self::getItemsInfoByIds($itemIds);
                if($ItemsInfo && is_array($ItemsInfo)){
                    foreach($ItemsInfo as $itemId=> $ItemInfo){
//                        $wikiId =   SelectionLib::updateWikiInfo($itemId , []);;
//                        $ItemInfo['wiki_id'] = $wikiId;
                        SelectionLib::updateItemInfo($itemId ,$ItemInfo);
                        CacheSelectionLib::setGoodsPriceById($itemId , $ItemInfo['zk_final_price']);
                    }
                }
        }
    }

    /*更新商品价格信息
     * @param itemId
     * @param price
     * */
    public   static function  updatePriceByItemId($itemId , $zk_final_price)
    {
        if(empty($itemId) || empty( $zk_final_price)) return false;
        $ItemInfo = mSelectionLib::getInfoByitemId($itemId);
        if(empty($ItemInfo)) return false;
        self::updateItemInfo($itemId , ['zk_final_price' => $zk_final_price]);
        CacheSelectionLib::setGoodsPriceById($itemId , $zk_final_price);
        return true;
    }

    /*wikiInfo 信息插入 或更新
     *
     * */
    public static function updateWikiInfo($itemId , $cateInfo){
        $url = RealUrl::formatLink($itemId,RealUrl::URL_TYPE_TAOBAO);
        $wikiInfo = \Biz\service\wiki\Wiki::getWikiByLink($url, null);
        if($cateInfo && is_array($cateInfo)){
            mWiki::updateData(
               $cateInfo,[
                    'id' => $wikiInfo['id']
                ]
            );
            mWikiBasic::updateData($cateInfo , ['id' => $wikiInfo['basic_id']]);
        }
        return $wikiInfo['id'];
    }

    /*插入selectionLib 库里
     * */
    public static function updateItemInfo($itemId , $updateData ,$wikiId = 0){
        $ItemInfo = mSelectionLib::getInfoByitemId($itemId);
        //是否有 status
        if($wikiId){
            $updateData['select_status'] = mSelectionLib::STATUS_WAIT_CHECK;
            $wikiInfo = \Biz\model\wiki\Wiki::getByWhere(['id' => $wikiId] , ['status']);
            if($wikiInfo && $wikiInfo['status'] > 0){
                $updateData['select_status'] =$wikiInfo['status'];
            }
        }
        //是否有 status
        if($ItemInfo){
            mSelectionLib::updateData($updateData , ['id' => $ItemInfo['id']]);
        }else{

            mSelectionLib::insertData($updateData);
        }
        return $itemId;
    }

    /*插入selectionLib 库里
     * */
    public static function updateItemByWikiId($wiki_id , $updateData){
        $ItemInfo = mSelectionLib::getByWhere(['wiki_id' => $wiki_id]);
        if($ItemInfo) {
           $result =  mSelectionLib::updateData($updateData, ['id' => $ItemInfo['id']]);
        }
        return $result;
    }

    /*从淘宝联盟获取信息
     *
     * */
    public static function getItemsInfoByIds($ItemIds){
        if(empty($ItemIds)) return [];
        $ItemsInfo = [];
        $ItemIdsStr = implode(',' ,$ItemIds);
        $scraperWikiInfo = TbkUnion::getItemsInfo($ItemIdsStr);
        if (empty($scraperWikiInfo)) {
            Log::wiki_getTaoBaoInfoByItemId_warning('获取不到信息:' .$ItemIdsStr);
            return false;
        }
        $scraperWikiInfo = array_combine(array_column($scraperWikiInfo , 'num_iid') , $scraperWikiInfo);
        if($scraperWikiInfo && is_array($scraperWikiInfo)) {
            foreach($ItemIds as $id){
                if(empty($scraperWikiInfo[$id])) continue;
                $ItemsInfo[$id] = [
                    'cat_name' => $scraperWikiInfo[$id]['cat_name'],
                    'cat_leaf_name' => $scraperWikiInfo[$id]['cat_leaf_name'],
                    'free_shipment' => $scraperWikiInfo[$id]['free_shipment'] ? 1 : 0,
                    'hot_flag' => $scraperWikiInfo[$id]['hot_flag'],
                    //聚划算
                    'ju_online_end_time' => $scraperWikiInfo[$id]['ju_online_end_time'],
                    'ju_online_start_time' => $scraperWikiInfo[$id]['ju_online_start_time'],
                    'ju_pre_show_end_time' => $scraperWikiInfo[$id]['ju_pre_show_end_time'],
                    'ju_pre_show_start_time' => $scraperWikiInfo[$id]['ju_pre_show_start_time'],
                    //聚划算
                    'material_lib_type' => $scraperWikiInfo[$id]['material_lib_type'],
                    'shop_name' => $scraperWikiInfo[$id]['nick'],
                    'pic_url' => $scraperWikiInfo[$id]['pict_url'], // 商品主图
                    'small_images' => implode(',', $scraperWikiInfo[$id]['small_images']['string']),
                    'superior_brand' => $scraperWikiInfo[$id]['superior_brand'],
                    'title' => $scraperWikiInfo[$id]['title'],
                    'tmall_play_activity_end_time' => $scraperWikiInfo[$id]['tmall_play_activity_end_time'],
                    'tmall_play_activity_start_time' => $scraperWikiInfo[$id]['tmall_play_activity_start_time'],
                    //月销
                    'volume' => $scraperWikiInfo[$id]['volume'],
                    //price
                    'zk_final_price' => $scraperWikiInfo[$id]['zk_final_price'],
                    'reserve_price' => $scraperWikiInfo[$id]['reserve_price'],
                    'seller_id' => $scraperWikiInfo[$id]['seller_id'],
                    //预售
                    'presale_deposit' => $scraperWikiInfo[$id]['presale_deposit'],
                    'presale_end_time' => $scraperWikiInfo[$id]['presale_end_time'],
                    'presale_start_time' => $scraperWikiInfo[$id]['presale_start_time'],
                    'presale_tail_end_time' => $scraperWikiInfo[$id]['presale_tail_end_time'],
                    'presale_tail_start_time' => $scraperWikiInfo[$id]['presale_tail_start_time'],
                    //预售
                    'provcity' => $scraperWikiInfo[$id]['provcity'],
                    'itemId' => $id,
                    'item_url' => $scraperWikiInfo[$id]['item_url']
                ];
                //price 处理
                $maxPrice = max($scraperWikiInfo[$id]['zk_final_price'], $scraperWikiInfo[$id]['reserve_price']);
                $minPrice = min($scraperWikiInfo[$id]['zk_final_price'], $scraperWikiInfo[$id]['reserve_price']);
                $ItemsInfo[$id]['max_price'] = $maxPrice;
                $ItemsInfo[$id]['min_price'] = $minPrice;

            }

        }
        return $ItemsInfo;
    }


    /*处理CateGroy
     *
     * */
    public static function getCateInfo($cat_name , $itemId){
        $cateInfo = [];
        $WikiInfo = [];
        $WikiInfo =   mWiki::getByWhere(['channel_spu_id' => $itemId]);
        //wikiInfo 存在  已有信息丛原来处获取
        if($WikiInfo['category_id']){
            $cateInfo = [
                'category_id' => $WikiInfo['category_id'],
                'second_category_id' =>  $WikiInfo['second_category_id'],
                'third_category_id' => $WikiInfo['third_category_id'],
                'four_category_id' =>  $WikiInfo['four_category_id'],
                'last_category_id' => $WikiInfo['last_category_id'],
            ];
        }else{
            if(empty(self::$cate_map)){
                self::setCateMap();
            }
            $cat_name_arr = isset(self::$cate_map[$cat_name]) ?self::$cate_map[$cat_name] : '';
            if(empty($cat_name_arr)) return[];
            $father_cate_name = $cat_name_arr['father_cate_name'];
            $father_cate_id = Category::getCategoryIdByName($father_cate_name);
            if(empty($father_cate_id)) return [];
            $cateId = Category::get( "id",
                ['status' => Category::STATUS_USING,
            'cate_name' => $cat_name_arr['cate_name'],'father_id' => $father_cate_id]
            );
            if($cateId){
                $cateTreeInfo =   Category::getTreeArrById($cateId);
                if($cateTreeInfo && is_array($cateTreeInfo)){
                    $cateInfo['category_id'] = $cateTreeInfo[0]['id'];
                    $cateInfo['last_category_id'] =  $cateInfo['category_id'];
                    $cateInfo['second_category_id'] = isset($cateTreeInfo[1]['id']) ? $cateTreeInfo[1]['id']: 0;
                    $cateInfo['last_category_id'] = $cateInfo['second_category_id']?:$cateInfo['last_category_id'];
                    $cateInfo['third_category_id'] = isset($cateTreeInfo[2]['id']) ? $cateTreeInfo[2]['id']: 0;
                    $cateInfo['last_category_id'] = $cateInfo['third_category_id']?:$cateInfo['last_category_id'];
                    $cateInfo['four_category_id'] = isset($cateTreeInfo[3]['id']) ?  $cateTreeInfo[3]['id']: 0;
                    $cateInfo['last_category_id'] = $cateInfo['four_category_id']?:$cateInfo['last_category_id'];
                }
            }else{
                Log::wiki_getCate_warning('无法获取导对应的分类信息' .$itemId);
            }
        }
        return $cateInfo;
    }

}
